package models

import (
	"database/sql"
	"time"
)

type MenuModel struct {
	Id int64`db:"id",json:"id"`
	Name string`db:"name",json:"name"`
	Path string`db:"string",json:"path"`
	Pid int64`db:"pid",json:"pid"`
	Hidden uint8`db:"hidden",json:"hidden"` // 0隐藏1显示
	Type uint8`db:"type",json:"type"` // 菜单类型 1导航菜单2按钮菜单
	Level uint8`db:"level",json:"level"` // 菜单层级
	CreateAt int64  `db:"create_at",json:"create_at"`
	UpdateAt int64  `db:"update_at",json:"update_at"`
}

func CreateMenu(db *sql.DB, name, path string, pid int64, hidden, mtype, level uint8) (bool, error) {
	sqlStr := "INSERT INTO `u_menus` (`name`,`path`,`pid`,`type`,`hidden`,`level`,`create_at`,`update_at`) VALUES (?,?,?,?,?,?,?,?)"
	now := time.Now().Unix()
	res,err := db.Exec(sqlStr,name,path,pid,mtype,hidden,level,now,now)
	if err != nil {
		return false,err
	}
	rows,err := res.RowsAffected()
	if err != nil {
		return false,err
	}
	return rows==1, nil
}

func GetMenus(db *sql.DB,uid int64) ([]MenuModel,error) {
	sqlStr := "SELECT * FROM `u_menus`"
	rows,err := db.Query(sqlStr)
	if err != nil {
		return nil,err
	}
	var menus []MenuModel
	for rows.Next() {
		var menu MenuModel
		_ = rows.Scan(&menu.Id,&menu.Name,&menu.Path,&menu.Pid,&menu.Level,&menu.Hidden,&menu.Pid,&menu.CreateAt,&menu.UpdateAt)
		menus = append(menus,menu)
	}
	return menus,nil
}